const { exec } = require('child_process');
const path = require('path');

// 1. 指定工作目录
const workspace = path.resolve(__dirname);
console.log(workspace)

// 2. 更安全的执行函数
function runCommand(cmd, options = {}) {
  return new Promise((resolve, reject) => {
    exec(cmd, { ...options, cwd: workspace }, (error, stdout, stderr) => {
      if (error) {
        console.error(`[ERROR] 执行失败: ${cmd}`);
        console.error(stderr);
        return reject(error);
      }
      console.log(`[SUCCESS] ${cmd}`);
      console.log(stdout);
      resolve(stdout);
    });
  });
}

// 3. 分步执行并处理错误
async function buildAndPush() {
  try {
    await runCommand('npm run docs:build');
    await runCommand('git add .');
    await runCommand('git commit -m "docs: auto update documentation"');
    await runCommand('git push');
    console.log('所有操作完成');
  } catch (error) {
    console.error('流程中断:', error.message);
    process.exit(1);
  }
}

// 4. 立即执行（移除了无意义的setTimeout）
buildAndPush();